package com.woniuxy.movie.gateway.filter;

import com.woniuxy.movie.commons.core.util.JwtUtil;
import com.woniuxy.movie.gateway.config.AuthenUrlProperties;
import com.woniuxy.movie.gateway.exception.AuthenException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

@Component
@Order(2)
public class UserLoginAuthenFilter implements GlobalFilter {

    @Autowired
    private AuthenUrlProperties aup;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String url = exchange.getRequest().getPath().toString();
        //判断是否是公共的放行的url
        if (AdminLoginAuthenFilter.match(aup,url)) {
            return chain.filter(exchange);
        }
        if (aup.matchUser(url)) {
            return chain.filter(exchange);
        }
        int index = url.lastIndexOf(".");
        if (index!=-1&&url.substring(index).equals(".api")) {
            return chain.filter(exchange);
        }
        //认证
        System.out.println("---------开始认证用户端登录状态--------------");
        List<String> tokens = exchange.getRequest().getHeaders().get("authen_token");
        if (tokens==null||tokens.size()<=0) {
            throw new AuthenException(401,"未登录");
        }
        String token = tokens.get(0);
        try {
            JwtUtil.parseUserToken(token);
        } catch (Exception e) {
            e.printStackTrace();
            throw new AuthenException(401,"未登录");
        }
        return chain.filter(exchange);
    }
}
